package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDAO;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.DictDAO;
import com.atguigu.entity.Dict;
import com.atguigu.service.DictService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @PACKAGE_NAME: com.atguigu.service.impl
 * @CLASSNAME: DictServiceImpl
 * @AUTHOR: zhangsan
 * @DATE: 2024/4/21 17:37
 * @SINCE 17.0.7
 * @DESCRIPTION: DictServiceImpl
 */
@Service(interfaceClass = DictService.class)
public class DictServiceImpl extends BaseServiceImpl<Dict> implements DictService {

    @Resource
    private DictDAO dictDAO;

    @Override
    protected BaseDAO<Dict> getEntityDAO() {
        return dictDAO;
    }

    /**
     * 通过id查找该节点的子节点
     *
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> findZnodes(Long id) {
        // 返回数据[{id:2,isParent:true,name:"随意勾选"}]
        //1 根据id获取子节点数据
        List<Dict> dictList = dictDAO.findListByParentId(id);
        //2 通过循环转换为指定json格式(其中要判断该节点是否是父节点)
        List<Map<String, Object>> zNodes = new ArrayList<>();
        dictList.forEach(dict -> {
            Integer count = dictDAO.countIsParent(dict.getId());
            Map<String, Object> map = new HashMap<>(3);
            map.put("id", dict.getId());
            map.put("name", dict.getName());
            map.put("isParent", count > 0);
            zNodes.add(map);
        });
        return zNodes;
    }

    /**
     * 根据父节点编码dictCode获取子节点列表
     *
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findListByDictCode(String dictCode) {
        Dict dict = dictDAO.getDictByDictCode(dictCode);
        if (null == dict) {
            return null;
        }
        List<Dict> dictList = dictDAO.findListByParentId(dict.getId());
        return dictList;
    }

    /**
     * 根据编码获取对应的数据字典
     *
     * @param dictCode
     * @return
     */
    @Override
    public Dict getDictByDictCode(String dictCode) {
        Dict dict = dictDAO.getDictByDictCode(dictCode);
        return dict;
    }

    /**
     * 根据字典id获取对应的名字
     *
     * @param id
     * @return
     */
    @Override
    public String getNameById(Long id) {
        String dictName = dictDAO.getNameById(id);
        return dictName;
    }


    /**
     * 根据父节点id获取子节点列表
     *
     * @param parentId
     * @return
     */
    @Override
    public List<Dict> findListByParentId(Long parentId) {
        List<Dict> dictList = dictDAO.findListByParentId(parentId);
        return dictList;
    }

    @Override
    public List<Dict> findChildrenById(Long id) {
        List<Dict> dictList = dictDAO.findChildrenById(id);
        return dictList;
    }
}
